package tom.spring.cloud.provider.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.stream.Stream;

/**
 * @author ZHUFEIFEI
 */
@Slf4j
@RestController
public class HelloController {

    @GetMapping("hello/sleuth")
    public String hello() {
        log.info("hello sleuth invoked!");
        return "hello, sleuth!";
    }

    @GetMapping("num")
    public String num(@RequestParam("num") int num) {
        return "your num : " + num;
    }

    @GetMapping("hello")
    public String hi(HttpServletRequest request, HttpServletResponse response) {
        request.getParameterMap().forEach((k, varr) -> {log.info("request param => {}={}", k, String.join(",", varr));});
        String hk;
        Enumeration<String> hn = request.getHeaderNames();
        while (hn.hasMoreElements()) {
            hk = hn.nextElement();
            log.info("request header => {}={}", hk, request.getHeader(hk));
        }
        //value是个数组
        response.addHeader("headerHello", "a");
        response.addHeader("headerHello", "b");
        response.addHeader("headerHello", "a");
        response.addHeader("headerHello", "b");
        response.addHeader("password", "123456");
        return "hello!";
    }

    @GetMapping("hystrix")
    public String hystrix() throws Exception {
        Thread.sleep(RandomUtils.nextInt(10) * 1000L);
        return "hystrix!";
    }

    @RequestMapping("fallback")
    public String fallback() throws Exception {
        return "fallback from provider02-sleuth!";
    }

    @GetMapping("limit/hi")
    public String limit() {
        log.info("==> limit!");
        return "limit!";
    }
}
